package com.jikedaquan.game.jwt.controller;


import com.alibaba.fastjson.JSON;

import com.jikedaquan.game.jwt.entity.User;
import com.jikedaquan.game.jwt.mapper.UserMapper;
import com.jikedaquan.game.jwt.util.MD5Tools;
import com.jikedaquan.game.jwt.util.VerifyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.jikedaquan.game.jwt.util.MD5Tools.string2MD5;

@Controller
@RequestMapping("/userLogin")
public class UserLoginController {

    private String rootPath = "/userLogin";
    @Autowired
    private UserMapper userMapper;

    @RequestMapping({"/index", "/"})
    public String Index() {
        return "login";
    }

    @RequestMapping({"/register"})
    public String Register() {
        return "register";
    }

    /**
     * 用户登录
     *
     * @param model   存储成功登录的用户 信息
     * @param session 存储标记 tag 代表登陆过 userID 标记当前登录的用户id 防止查阅他人信息
     * @param userId  当前查阅的用户id
     * @return
     */
    @RequestMapping({"/success/{userId}"})
    public String Success(Model model, HttpSession session, @PathVariable("userId") Integer userId) {
        String tag = (String) session.getAttribute("tag");
        Integer userID = (Integer) session.getAttribute("userID");
        String path = "redirect:" + rootPath + "/index";
        if (null == tag || null == userId || null == userID) {
            return path;
        }
        if (tag.equals("success") && (userId == userID)) {
            User user = userMapper.selectById(userId);
            model.addAttribute("userInfo", user);
            return "success";
        }
        return path;
    }

    @PostMapping(value = "/toLogin")
    @ResponseBody
    public String toLogin(@RequestBody Map<String, Object> requestMap, HttpServletRequest request) {
        System.out.println("requestMap>>>" + requestMap);
        Map<String, String> reMap = new HashMap<String, String>();
        String loginName = (String) requestMap.get("loginName");
        String loginPwd = (String) requestMap.get("loginPwd");
        String msg = "消息";
        String path = rootPath + "/index";
        if (null == loginName || null == loginPwd || "".equals(loginName) || "".equals(loginPwd)) {
            msg = "用户名或密码为空";
        } else {
            String newPwd = string2MD5(loginPwd);
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("account", loginName);//写表中的列名
            columnMap.put("password", newPwd);
            List<User> employees = userMapper.selectByMap(columnMap);
            System.out.println(employees.size());
            if (employees.size() == 1) {
                User user = employees.get(0);
                HttpSession session = request.getSession();
                session.setAttribute("tag", "success");
                //防止输入他人id
                session.setAttribute("userID", user.getId());
                msg = "登录成功！";
                path = rootPath + "/success/" + user.getId();
            } else {
                msg = "用户名或密码错误！";
            }
        }
        reMap.put("path", path);
        reMap.put("msg", msg);
        // 跳转路径 返回错误信息
        return JSON.toJSONString(reMap);
    }

    @PostMapping(value = "/toRegister")
    @ResponseBody
    public String toRegister(@RequestBody Map<String, Object> requestMap, HttpServletRequest request) {
        System.out.println("requestMap>>>" + requestMap);
        Map<String, String> reMap = new HashMap<String, String>();
        String loginName = (String) requestMap.get("loginName");
        String loginUserName = (String) requestMap.get("loginUserName");
        String loginPwd = (String) requestMap.get("loginPwd");
        String msg = "消息";
        String path = rootPath + "/register";
        if (null == loginName || null == loginPwd || null == loginUserName || "".equals(loginName) || "".equals(loginPwd) || "".equals(loginUserName)) {
            msg = "请检查必填项！";
        } else {
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("account", loginName);//写表中的列名
            List<User> sqlUserList = userMapper.selectByMap(columnMap);
            if (sqlUserList.size() > 0) {
                msg = "该登录名已被使用！";
            } else {
                String newPwd = string2MD5(loginPwd);
                //初始化新增用户
                User user = new User();
                user.setUserName(loginUserName).setAccount(loginName).setPassword(newPwd);
//           user.setStatus(); 数据库与字段不符
                user.setMoney(0).setLevel(0).setYp(0).setYb(0).setExp(0).setTl(0).setExcited(0);
                int reCount = userMapper.insert(user);
                if (reCount == 1) {
                    msg = "恭喜您，注册成功！";
                    //待确定 直接跳转登录成功页面还是 跳转登录页面
                    path = rootPath + "/index";
                } else {
                    msg = "注册失败，给您带来不便，很抱歉！";
                }
            }
        }
        reMap.put("path", path);
        reMap.put("msg", msg);
        // 跳转路径 返回错误信息
        return JSON.toJSONString(reMap);
    }


    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            VerifyUtil randomValidateCode = new VerifyUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            System.out.println("获取验证码失败>>>>   " + e);
        }
    }

    /**
     * 校验验证码
     */
    @RequestMapping(value = "/checkVerify", method = RequestMethod.POST, headers = "Accept=application/json")
    @ResponseBody
    public boolean checkVerify(@RequestBody Map<String, Object> requestMap, HttpSession session) {
        try {
            //从session中获取随机数
            String inputStr = requestMap.get("inputStr").toString();
            String random = (String) session.getAttribute("RANDOMVALIDATECODEKEY");
            inputStr = inputStr.toUpperCase();
            if (random == null) {
                return false;
            }
            if (random.equals(inputStr)) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            System.out.println("验证码校验失败>>>>   " + e);
            return false;
        }
    }
}
